/*
 * common.js
 * create by Charles Koh
 */

var spaces = /\s+/, a1 = [""], ajax;
function trim(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};

function str2array(s) {
	if (typeof s == "string" || s instanceof String) {
		if (s.indexOf(" ") < 0) {
			a1[0] = s;
			return a1;
		} else {
			return s.split(spaces);
		}
	}
	return s;
}

function addClass(node, classStr) {
	classStr = str2array(classStr);
	var cls = node.className;
	for (var i = 0, len = classStr.length, c; i < len; ++i) {
		c = classStr[i];
		if (c && cls.indexOf(c) < 0) {
			cls += " " + c;
		}
	}
	node.className = trim(cls);
}

function removeClass(node, classStr) {
	var cls;
	if (classStr !== undefined) {
		classStr = str2array(classStr);
		cls = node.className;
		for (var i = 0, len = classStr.length; i < len; ++i) {
			cls = cls.replace(classStr[i], "");
		}
		cls = trim(cls);
	} else {
		cls = "";
	}
	if (node.className != cls) {
		node.className = cls;
	}
}

function addEvent(target, event, callback, bubbling) {
	if (target.addEventListener)
		target.addEventListener(event, callback, bubbling);
	else
		attachEvent(event, callback);	// only IE
}

function removeEvent(target, event, callback, bubbling) {
	if (target.removeEventListener)
		target.removeEventListener(event, callback, bubbling);
	else
		target.detachEvent(event, callback);	// only IE
}

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}


(function () {
	var Ajax = function(){
		this.xhr = window.ActiveXObject ?
			/* Microsoft failed to properly
			 * implement the XMLHttpRequest in IE7 (can't request local files),
			 * so we use the ActiveXObject when it is available
			 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
			 * we need a fallback.
			 * !this.isLocal && createStandardXHR() || createActiveXHR() : createStandardXHR();
			 */
			createActiveXHR() : createStandardXHR();
			
		//default option
		this.options = {
			data: null,
			type: "GET",
			dataType:"html"
		};
	};
	
	Ajax.prototype = {
		request: function (option) {
			var thisClass = this,
				params = option.data,
				serverRequest = option.url,
				default_option = {
				};
				
			for (i in option) thisClass.options[i] = option[i];
			
			if (thisClass.options.type.toUpperCase() == "GET") {
				serverRequest = serverRequest + "?" + params;
			} else {
				//Send the proper header information along with the request
				thisClass.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				thisClass.xhr.setRequestHeader("Content-length", params.length);
				thisClass.xhr.setRequestHeader("Connection", "close");
			}
			
			thisClass.xhr.onreadystatechange = function () {
				if(this.readyState == 4 && this.status == 200) {
					// so far so good
					if(this.responseText) // success!
		   				if (typeof(thisClass.options.successCB) == typeof(function(){})) thisClass.options.successCB(thisClass.ajaxConvert(thisClass.options.dataType, this.responseText));
		  			else
		   				if (typeof(thisClass.options.failCB) == typeof(function(){})) thisClass.options.failCB(this.status);
		 		} else if (this.readyState == 4 && this.status != 200) {
		  			if (typeof(thisClass.options.failCB) == typeof(function(){})) thisClass.options.failCB(this.status);
		 		}
			};
			thisClass.xhr.open(thisClass.options.type.toUpperCase(), serverRequest);
			thisClass.xhr.send(params || null);
		},
		parseJSON: function (data) {
			// Attempt to parse using the native JSON parser first
			if ( window.JSON && window.JSON.parse ) {
				return window.JSON.parse( data );
			}
		},
		parseXML: function (data) {
			var xml, tmp;
			try {
				if ( window.DOMParser ) { // Standard
					tmp = new DOMParser();
					xml = tmp.parseFromString( data , "text/xml" );
				} else { // IE
					xml = new ActiveXObject( "Microsoft.XMLDOM" );
					xml.async = "false";
					xml.loadXML( data );
				}
			} catch( e ) {
				xml = undefined;
			}
			return xml;
		},
	
		ajaxConvert: function(type, data) {
			var response;
			switch (type.toLowerCase()) {
				case "html": 
				response = data;
				break;
				case "json":
				response = this.parseJSON(data);
				break;
				case "xml":
				response = this.parseXML(data);
				break;
			}
			return response;
		}
	};
	
    if (typeof exports !== 'undefined') exports.Ajax = Ajax;
    else window.Ajax = Ajax;
    
    ajax = new Ajax();
})();


